import React, { useState, useEffect, useCallback, useMemo } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  Modal,
  FlatList,
  TextInput,
  Alert,
  StyleSheet,
  ActivityIndicator,
} from 'react-native'

export interface User {
  id: string | number
  nickname: string
  deptIds?: number[]
  deptNames?: string[]
  posts?: Array<{
    id: string
    name: string
  }>
}

export interface Department {
  id: number
  name: string
  parentId?: number
  children?: Department[]
}

interface LeaderSelectorProps {
  visible: boolean
  onClose: () => void
  onConfirm: (selectedUsers: User[]) => void
  multiple?: boolean
  title?: string
  selectedUserIds?: string[]
  // 新增部门相关属性
  showDeptFilter?: boolean
  deptId?: number | number[]
  currentUserId?: number
}

// 全局缓存
let cachedDeptList: Department[] = []
let cachedUserList: User[] = []
let cacheTimestamp = 0
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

export const LeaderSelector: React.FC<LeaderSelectorProps> = ({
  visible,
  onClose,
  onConfirm,
  multiple = false,
  title = '选择领导',
  selectedUserIds = [],
  showDeptFilter = true,
  deptId,
  currentUserId,
}) => {
  const [userList, setUserList] = useState<User[]>([])
  const [filteredUsers, setFilteredUsers] = useState<User[]>([])
  const [searchText, setSearchText] = useState('')
  const [selectedUsers, setSelectedUsers] = useState<User[]>([])
  const [isLoading, setIsLoading] = useState(false)

  // 新增部门相关状态
  const [deptList, setDeptList] = useState<Department[]>([])
  const [deptTree, setDeptTree] = useState<Department[]>([])
  const [selectedDeptId, setSelectedDeptId] = useState<number | null>(null)

  // 检查缓存是否有效
  const isCacheValid = useCallback(() => {
    const now = Date.now()
    return cachedDeptList.length > 0 && cachedUserList.length > 0 && (now - cacheTimestamp) < CACHE_DURATION
  }, [])

  // 加载部门和用户数据
  const loadData = useCallback(async () => {
    setIsLoading(true)
    try {
      let depts: Department[] = []
      let users: User[] = []

      // 检查缓存
      if (isCacheValid()) {
        console.log('使用缓存数据')
        depts = cachedDeptList
        users = cachedUserList
      } else {
        console.log('从服务器加载数据')

        // 并行加载部门和用户数据
        const [{ DeptApi }, { UserApi }] = await Promise.all([
          import('../api/dept'),
          import('../api/user')
        ])

        const [deptResponse, userResponse] = await Promise.all([
          DeptApi.getSimpleDeptList(),
          UserApi.getSimpleUserList()
        ])

        if (deptResponse.code === 0 && deptResponse.data) {
          depts = deptResponse.data
          cachedDeptList = depts
        } else {
          console.error('部门API返回错误:', deptResponse.msg)
          throw new Error(deptResponse.msg || '获取部门列表失败')
        }

        if (userResponse.code === 0 && userResponse.data) {
          users = userResponse.data
          cachedUserList = users
          cacheTimestamp = Date.now()
        } else {
          console.error('用户API返回错误:', userResponse.msg)
          throw new Error(userResponse.msg || '获取用户列表失败')
        }
      }

      // 处理部门数据
      setDeptList(depts)

      if (deptId) {
        const deptIdArray = Array.isArray(deptId) ? deptId : [deptId]
        const filteredDepts = depts.filter((dept: Department) => deptIdArray.includes(dept.id))
        setDeptTree(buildDeptTree(filteredDepts))

        // 自动选择第一个部门
        if (filteredDepts.length > 0) {
          setSelectedDeptId(filteredDepts[0].id)
        }
      } else {
        const tree = buildDeptTree(depts)
        setDeptTree(tree)
      }

      // 处理用户数据
      let filteredUsers = users

      // 如果有指定部门ID，则过滤用户
      if (deptId) {
        const deptIdArray = Array.isArray(deptId) ? deptId : [deptId]
        filteredUsers = filteredUsers.filter(user => {
          if (user.deptIds && Array.isArray(user.deptIds)) {
            return user.deptIds.some((id: number) => deptIdArray.includes(id))
          }
          return false
        })
      }

      // 如果有当前用户ID，则排除当前用户
      if (currentUserId) {
        filteredUsers = filteredUsers.filter(user => user.id !== currentUserId)
      }

      setUserList(filteredUsers)
      setFilteredUsers(filteredUsers)

    } catch (error) {
      console.error('加载数据失败:', error)
      Alert.alert('错误', error instanceof Error ? error.message : '获取数据失败，请检查网络连接')
      setUserList([])
      setFilteredUsers([])
    } finally {
      setIsLoading(false)
    }
  }, [deptId, currentUserId, isCacheValid])

  useEffect(() => {
    if (visible) {
      loadData()
    }
  }, [visible, loadData])

  useEffect(() => {
    // 根据已选择的用户ID初始化选中状态
    if (visible && selectedUserIds.length > 0 && userList.length > 0) {
      const preSelected = userList.filter(user =>
        selectedUserIds.includes(String(user.id))
      )
      setSelectedUsers(preSelected)
    } else if (visible) {
      // 如果没有选中的用户ID，清空选中状态
      setSelectedUsers([])
    }
  }, [visible, selectedUserIds, userList])

  // 使用 useMemo 优化搜索过滤
  const filteredUserList = useMemo(() => {
    if (!searchText.trim()) {
      return userList
    }

    const searchLower = searchText.toLowerCase()
    return userList.filter(user => {
      // 搜索昵称
      if (user.nickname.toLowerCase().includes(searchLower)) return true

      // 搜索部门名称
      if (user.deptNames?.some(name => name.toLowerCase().includes(searchLower))) return true

      return false
    })
  }, [searchText, userList])

  useEffect(() => {
    setFilteredUsers(filteredUserList)
  }, [filteredUserList])

  // 构建部门树形结构（使用 useMemo 优化）
  const buildDeptTree = useCallback((depts: Department[]): Department[] => {
    const deptMap = new Map<number, Department>()
    const roots: Department[] = []

    // 创建部门映射
    depts.forEach(dept => {
      deptMap.set(dept.id, { ...dept, children: [] })
    })

    // 构建树形结构
    depts.forEach(dept => {
      if (dept.parentId && deptMap.has(dept.parentId)) {
        const parent = deptMap.get(dept.parentId)!
        parent.children!.push(deptMap.get(dept.id)!)
      } else {
        roots.push(deptMap.get(dept.id)!)
      }
    })

    return roots
  }, [])

  // 获取部门及其子部门的所有用户
  const getUsersByDept = (deptId: number): User[] => {
    const deptIds = getChildDeptIds(deptId)
    return userList.filter(user => {
      if (user.deptIds && Array.isArray(user.deptIds)) {
        return user.deptIds.some((id: number) => deptIds.includes(id))
      }
      return false
    })
  }

  // 获取子部门ID列表
  const getChildDeptIds = (deptId: number): number[] => {
    const ids = [deptId]
    const children = deptList.filter(dept => dept.parentId === deptId)
    children.forEach(child => {
      ids.push(...getChildDeptIds(child.id))
    })
    return ids
  }

  // 选择部门
  const selectDept = (dept: Department) => {
    setSelectedDeptId(dept.id)
    const users = getUsersByDept(dept.id)
    setFilteredUsers(users)
  }

  const handleUserSelect = (user: User) => {
    if (multiple) {
      const isSelected = selectedUsers.some(u => String(u.id) === String(user.id))
      if (isSelected) {
        setSelectedUsers(selectedUsers.filter(u => String(u.id) !== String(user.id)))
      } else {
        setSelectedUsers([...selectedUsers, user])
      }
    } else {
      setSelectedUsers([user])
    }
  }

  const handleConfirm = () => {
    onConfirm(selectedUsers)
    onClose()
  }

  const handleCancel = () => {
    setSelectedUsers([])
    setSearchText('')
    onClose()
  }

  const renderDeptItem = ({ item }: { item: Department }) => {
    // 计算缩进层级
    const getIndentLevel = (dept: Department): number => {
      let level = 0
      let currentDept = dept
      while (currentDept.parentId && deptList.find(d => d.id === currentDept.parentId)) {
        level++
        currentDept = deptList.find(d => d.id === currentDept.parentId)!
      }
      return level
    }

    const indentLevel = getIndentLevel(item)

    return (
      <TouchableOpacity
        style={[
          styles.deptItem,
          selectedDeptId === item.id && styles.selectedDeptItem
        ]}
        onPress={() => selectDept(item)}
      >
        <View style={[styles.deptItemContent, { paddingLeft: 16 + indentLevel * 16 }]}>
          <Text style={[
            styles.deptName,
            selectedDeptId === item.id && styles.selectedDeptName
          ]}>
            {item.name}
          </Text>
          {item.children && item.children.length > 0 && (
            <Text style={styles.deptCount}>({item.children.length})</Text>
          )}
        </View>
      </TouchableOpacity>
    )
  }

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={handleCancel}
    >
      <View style={styles.container}>
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity onPress={handleCancel}>
            <Text style={styles.cancelButton}>取消</Text>
          </TouchableOpacity>
          <Text style={styles.title}>{title}</Text>
          <TouchableOpacity onPress={handleConfirm}>
            <Text style={styles.confirmButton}>确定</Text>
          </TouchableOpacity>
        </View>

        {/* 主要内容区域 */}
        <View style={styles.mainContent}>
          {/* 左侧部门树 */}
          {showDeptFilter && (
            <View style={styles.deptTreeContainer}>
              <Text style={styles.deptTreeTitle}>选择部门</Text>
              <FlatList
                data={deptTree}
                keyExtractor={(item) => String(item.id)}
                renderItem={renderDeptItem}
                style={styles.deptTree}
                showsVerticalScrollIndicator={false}
                ListEmptyComponent={
                  <View style={styles.emptyContainer}>
                    <Text style={styles.emptyText}>暂无部门数据</Text>
                  </View>
                }
              />
            </View>
          )}

          {/* 右侧用户选择区域 */}
          <View style={styles.userSectionContainer}>
            {/* 搜索栏 */}
            <View style={styles.searchContainer}>
              <TextInput
                style={styles.searchInput}
                placeholder="搜索姓名、部门"
                value={searchText}
                onChangeText={setSearchText}
              />
            </View>

            {/* 已选择用户数量 */}
            {multiple && selectedUsers.length > 0 && (
              <View style={styles.selectedCount}>
                <Text style={styles.selectedCountText}>
                  已选择 {selectedUsers.length} 人
                </Text>
              </View>
            )}

            {/* 用户列表 */}
            {isLoading ? (
              <View style={styles.loadingContainer}>
                <ActivityIndicator size="large" color="#409EFF" />
                <Text style={styles.loadingText}>加载中...</Text>
              </View>
            ) : (
              <FlatList
                data={filteredUsers}
                keyExtractor={(item) => String(item.id)}
                renderItem={({ item }) => (
                  <TouchableOpacity
                    style={[
                      styles.userItem,
                      selectedUsers.some(u => String(u.id) === String(item.id)) && styles.selectedUserItem
                    ]}
                    onPress={() => handleUserSelect(item)}
                  >
                    <View style={styles.userInfo}>
                      <Text style={[
                        styles.userName,
                        selectedUsers.some(u => String(u.id) === String(item.id)) && styles.selectedUserName
                      ]}>
                        {item.nickname}
                      </Text>
                    </View>
                    {selectedUsers.some(u => String(u.id) === String(item.id)) && (
                      <View style={styles.checkIcon}>
                        <Text style={styles.checkText}>✓</Text>
                      </View>
                    )}
                  </TouchableOpacity>
                )}
                style={styles.userList}
                showsVerticalScrollIndicator={false}
                ListEmptyComponent={
                  <View style={styles.emptyContainer}>
                    <Text style={styles.emptyText}>
                      {searchText.trim() ? '未找到匹配的用户' : '暂无用户数据'}
                    </Text>
                  </View>
                }
              />
            )}
          </View>
        </View>
      </View>
    </Modal>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  cancelButton: {
    fontSize: 16,
    color: '#666',
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  confirmButton: {
    fontSize: 16,
    color: '#409EFF',
    fontWeight: '600',
  },
  // 部门选择器样式
  deptSelectorContainer: {
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  deptSelectorButton: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: '#f8f9fa',
  },
  deptSelectorButtonText: {
    fontSize: 16,
    color: '#333',
    fontWeight: '500',
  },
  deptSelectorArrow: {
    fontSize: 12,
    color: '#666',
  },
  deptListContainer: {
    maxHeight: 200,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#e5e5e5',
  },
  deptList: {
    flex: 1,
  },
  deptItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  selectedDeptItem: {
    backgroundColor: '#e3f2fd',
  },
  deptName: {
    fontSize: 16,
    color: '#333',
    flex: 1,
  },
  selectedDeptName: {
    color: '#1976d2',
    fontWeight: '500',
  },
  deptCount: {
    fontSize: 14,
    color: '#666',
    marginLeft: 8,
  },
  searchContainer: {
    padding: 16,
    backgroundColor: '#fff',
  },
  searchInput: {
    height: 50,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 12,
    fontSize: 16,
    backgroundColor: '#f9f9f9',
  },
  // 用户列表样式
  userList: {
    flex: 1,
    backgroundColor: '#fff',
  },
  userItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  selectedUserItem: {
    backgroundColor: '#f0f7ff',
  },
  userInfo: {
    flex: 1,
  },
  userName: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginBottom: 4,
  },
  selectedUserName: {
    color: '#409EFF',
  },
  userDetail: {
    fontSize: 14,
    color: '#666',
  },
  checkIcon: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: '#409EFF',
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 50,
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: '#666',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 50,
  },
  emptyText: {
    fontSize: 16,
    color: '#999',
  },
  debugText: {
    fontSize: 12,
    color: '#999',
    marginTop: 5,
    marginBottom: 5,
  },
  mainContent: {
    flexDirection: 'row',
    flex: 1,
  },
  deptTreeContainer: {
    width: 140, // 左侧部门树宽度
    backgroundColor: '#f0f0f0',
    paddingVertical: 10,
    borderRightWidth: 1,
    borderRightColor: '#e0e0e0',
  },
  deptTreeTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    paddingHorizontal: 16,
    paddingBottom: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  deptTree: {
    flex: 1,
  },
  userSectionContainer: {
    flex: 1,
    backgroundColor: '#fff',
  },
  deptItemContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectedCount: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5e5',
  },
  selectedCountText: {
    fontSize: 14,
    color: '#409EFF',
  },
})